"""
统一AI服务包装器
为缺少analyze_frame方法的AI服务提供统一接口
"""
import asyncio
import logging
import cv2
import numpy as np
from datetime import datetime
from typing import Dict, List, Any, Optional
import time

logger = logging.getLogger(__name__)


class UnifiedAIWrapper:
    """统一AI服务包装器"""
    
    def __init__(self, service_name: str, service_instance=None):
        self.service_name = service_name
        self.service_instance = service_instance
        logger.info(f"统一AI包装器初始化: {service_name}")
    
    async def analyze_frame(self, frame: np.ndarray, camera_id: str) -> Dict[str, Any]:
        """
        统一的帧分析接口
        
        Args:
            frame: 视频帧数据
            camera_id: 摄像头ID
            
        Returns:
            分析结果字典
        """
        try:
            start_time = time.time()
            
            # 基础结果模板
            result = {
                'camera_id': camera_id,
                'timestamp': datetime.now().isoformat(),
                'algorithm_type': self.service_name,
                'status': 'success',
                'detections': [],
                'metrics': {},
                'alerts': [],
                'processing_time': 0.0
            }
            
            # 根据服务类型进行不同的分析
            if 'crowd_safety' in self.service_name:
                result.update(await self._analyze_crowd_safety(frame, camera_id))
            elif 'energy_management' in self.service_name:
                result.update(await self._analyze_energy_management(frame, camera_id))
            elif 'classroom_quality' in self.service_name:
                result.update(await self._analyze_classroom_quality(frame, camera_id))
            elif 'teaching_assessment' in self.service_name:
                result.update(await self._analyze_teaching_assessment(frame, camera_id))
            else:
                result.update(await self._analyze_generic(frame, camera_id))
            
            # 计算处理时间
            result['processing_time'] = time.time() - start_time
            
            logger.debug(f"{self.service_name}分析完成: {camera_id}")
            return result
            
        except Exception as e:
            logger.error(f"{self.service_name}分析失败: {camera_id} - {e}")
            return {
                'camera_id': camera_id,
                'timestamp': datetime.now().isoformat(),
                'algorithm_type': self.service_name,
                'status': 'error',
                'error_message': str(e),
                'processing_time': time.time() - start_time if 'start_time' in locals() else 0.0
            }
    
    async def _analyze_crowd_safety(self, frame: np.ndarray, camera_id: str) -> Dict[str, Any]:
        """人群安全分析"""
        # 简化的人群检测
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        blurred = cv2.GaussianBlur(gray, (5, 5), 0)
        thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]
        contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        
        person_count = 0
        detections = []
        
        for i, contour in enumerate(contours):
            area = cv2.contourArea(contour)
            if area > 1000:  # 过滤小轮廓
                x, y, w, h = cv2.boundingRect(contour)
                if w > 30 and h > 50:  # 基本人形比例
                    person_count += 1
                    detections.append({
                        'id': f'person_{i}',
                        'class_name': 'person',
                        'confidence': 0.7,
                        'bbox': {'x1': x, 'y1': y, 'x2': x+w, 'y2': y+h}
                    })
        
        # 计算密度
        frame_area = frame.shape[0] * frame.shape[1]
        density = person_count / (frame_area / 10000)  # 每万像素的人数
        
        alerts = []
        if person_count > 10:
            alerts.append({
                'type': 'high_density',
                'level': 'high',
                'message': f'人群密度过高: {person_count}人',
                'timestamp': datetime.now().isoformat()
            })
        elif person_count > 5:
            alerts.append({
                'type': 'medium_density',
                'level': 'medium',
                'message': f'人群密度较高: {person_count}人',
                'timestamp': datetime.now().isoformat()
            })
        
        return {
            'person_count': person_count,
            'crowd_density': density,
            'density_level': 'high' if person_count > 10 else 'medium' if person_count > 5 else 'low',
            'detections': detections,
            'alerts': alerts
        }
    
    async def _analyze_energy_management(self, frame: np.ndarray, camera_id: str) -> Dict[str, Any]:
        """能源管理分析"""
        # 简化的亮度检测
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        avg_brightness = np.mean(gray)
        
        # 简化的占用检测
        thresh = cv2.threshold(gray, 60, 255, cv2.THRESH_BINARY)[1]
        contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        
        occupancy_objects = 0
        for contour in contours:
            if cv2.contourArea(contour) > 500:
                occupancy_objects += 1
        
        occupancy_rate = min(occupancy_objects / 10.0, 1.0)  # 最多10个对象为100%占用
        
        lighting_status = 'on' if avg_brightness > 100 else 'off'
        energy_efficiency = 0.8 if lighting_status == 'on' and occupancy_rate > 0.3 else 0.4
        
        alerts = []
        if lighting_status == 'on' and occupancy_rate < 0.1:
            alerts.append({
                'type': 'energy_waste',
                'level': 'medium',
                'message': '灯光开启但无人使用',
                'timestamp': datetime.now().isoformat()
            })
        
        return {
            'lighting_status': lighting_status,
            'occupancy_rate': occupancy_rate,
            'energy_efficiency': energy_efficiency,
            'avg_brightness': avg_brightness,
            'alerts': alerts
        }
    
    async def _analyze_classroom_quality(self, frame: np.ndarray, camera_id: str) -> Dict[str, Any]:
        """课堂质量分析"""
        # 简化的学生检测
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        thresh = cv2.threshold(gray, 60, 255, cv2.THRESH_BINARY)[1]
        contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        
        student_count = 0
        detections = []
        
        for i, contour in enumerate(contours):
            area = cv2.contourArea(contour)
            if 500 < area < 5000:  # 学生大小范围
                x, y, w, h = cv2.boundingRect(contour)
                if 20 < w < 100 and 40 < h < 150:  # 坐着的学生比例
                    student_count += 1
                    detections.append({
                        'id': f'student_{i}',
                        'class_name': 'student',
                        'confidence': 0.6,
                        'bbox': {'x1': x, 'y1': y, 'x2': x+w, 'y2': y+h}
                    })
        
        # 估算出勤率（假设教室容量30人）
        attendance_rate = min(student_count / 30.0, 1.0)
        quality_score = attendance_rate * 0.8 + 0.2  # 基础分数
        
        alerts = []
        if attendance_rate < 0.3:
            alerts.append({
                'type': 'low_attendance',
                'level': 'medium',
                'message': f'出勤率较低: {attendance_rate:.1%}',
                'timestamp': datetime.now().isoformat()
            })
        
        return {
            'quality_score': quality_score,
            'attendance_rate': attendance_rate,
            'student_count': student_count,
            'attention_level': 'medium',
            'detections': detections,
            'alerts': alerts
        }
    
    async def _analyze_teaching_assessment(self, frame: np.ndarray, camera_id: str) -> Dict[str, Any]:
        """教学质量评估分析"""
        # 简化的教师检测
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        thresh = cv2.threshold(gray, 60, 255, cv2.THRESH_BINARY)[1]
        contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        
        teacher_detected = False
        student_count = 0
        
        for contour in contours:
            area = cv2.contourArea(contour)
            x, y, w, h = cv2.boundingRect(contour)
            
            # 教师检测（较大的直立人形）
            if area > 2000 and h > w * 1.5:
                teacher_detected = True
            # 学生检测
            elif 500 < area < 2000:
                student_count += 1
        
        # 评估教学质量
        teaching_score = 0.7 if teacher_detected else 0.3
        if student_count > 5:
            teaching_score += 0.2
        
        interaction_level = 'high' if teacher_detected and student_count > 10 else 'medium' if teacher_detected else 'low'
        
        alerts = []
        if not teacher_detected:
            alerts.append({
                'type': 'no_teacher',
                'level': 'high',
                'message': '未检测到教师',
                'timestamp': datetime.now().isoformat()
            })
        
        return {
            'teaching_score': teaching_score,
            'interaction_level': interaction_level,
            'teacher_behavior': {'detected': teacher_detected, 'active': teacher_detected},
            'student_engagement': min(student_count / 20.0, 1.0),
            'alerts': alerts
        }
    
    async def _analyze_generic(self, frame: np.ndarray, camera_id: str) -> Dict[str, Any]:
        """通用分析"""
        # 基本的图像统计
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        avg_brightness = np.mean(gray)
        
        return {
            'avg_brightness': avg_brightness,
            'frame_size': {'width': frame.shape[1], 'height': frame.shape[0]},
            'analysis_type': 'generic'
        }


# 为各个服务创建包装器实例
def create_crowd_safety_wrapper():
    """创建人群安全服务包装器"""
    return UnifiedAIWrapper('crowd_safety')

def create_energy_management_wrapper():
    """创建能源管理服务包装器"""
    return UnifiedAIWrapper('energy_management')

def create_classroom_quality_wrapper():
    """创建课堂质量服务包装器"""
    return UnifiedAIWrapper('classroom_quality')

def create_teaching_assessment_wrapper():
    """创建教学评估服务包装器"""
    return UnifiedAIWrapper('teaching_assessment')